/**
 * 
 */
package com.lanswon.qzsmk.service.cardManageService.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import ch.qos.logback.classic.Logger;

import com.lanswon.qzsmk.base.AccountContants;
import com.lanswon.qzsmk.base.AppContants;
import com.lanswon.qzsmk.base.BlackListContants;
import com.lanswon.qzsmk.base.CardContants;
import com.lanswon.qzsmk.base.DwzPage;
import com.lanswon.qzsmk.base.HttpContants;
import com.lanswon.qzsmk.dao.AppKindMapper;
import com.lanswon.qzsmk.dao.AppOpenRegMapper;
import com.lanswon.qzsmk.dao.BlackListGenMapper;
import com.lanswon.qzsmk.dao.BlackListRcMapper;
import com.lanswon.qzsmk.dao.BusinessMapper;
import com.lanswon.qzsmk.dao.CardControlMapper;
import com.lanswon.qzsmk.dao.CardDataMapper;
import com.lanswon.qzsmk.dao.CardLossMapper;
import com.lanswon.qzsmk.dao.CardManageMapper;
import com.lanswon.qzsmk.dao.CardPhysicsTypeMapper;
import com.lanswon.qzsmk.dao.CardProdunctDefinitionMapper;
import com.lanswon.qzsmk.dao.CardTypeMapper;
import com.lanswon.qzsmk.dao.CertMapper;
import com.lanswon.qzsmk.dao.CertificateMapper;
import com.lanswon.qzsmk.dao.ChangeCardMapper;
import com.lanswon.qzsmk.dao.SubaccountPersonalMapper;
import com.lanswon.qzsmk.exception.ErrorCode;
import com.lanswon.qzsmk.model.ActiveUser;
import com.lanswon.qzsmk.model.AppKind;
import com.lanswon.qzsmk.model.AppOpenReg;
import com.lanswon.qzsmk.model.BlackListGen;
import com.lanswon.qzsmk.model.BlackListRc;
import com.lanswon.qzsmk.model.Business;
import com.lanswon.qzsmk.model.CardControl;
import com.lanswon.qzsmk.model.CardData;
import com.lanswon.qzsmk.model.CardManage;
import com.lanswon.qzsmk.model.Cert;
import com.lanswon.qzsmk.model.ChangeCard;
import com.lanswon.qzsmk.model.SubaccountPersonal;
import com.lanswon.qzsmk.service.cardManageService.LossAndUnbindService;
import com.lanswon.qzsmk.service.preService.BikeService;
import com.lanswon.qzsmk.util.SequenceNumberUtil;
import com.lanswon.qzsmk.vo.LossCardInfo;
import com.lanswon.qzsmk.vo.LossCardVo;
import com.lanswon.qzsmk.vo.ResultStatus;
import com.lanswon.qzsmk.vo.ResultVo;
import com.lanswon.qzsmk.vo.VoucherVo;

/**
 * @author sun
 *
 */
@Service
public class LossAndUnbindServiceImpl implements LossAndUnbindService {

	private static Logger logger = (Logger) LoggerFactory.getLogger(LossAndUnbindServiceImpl.class);
	
	@Autowired
	BikeService bikeService;

	@Autowired
	ChangeCardMapper ccm;

	@Autowired
	BlackListGenMapper blgm;

	@Autowired
	BlackListRcMapper blrm;

	@Autowired
	AppOpenRegMapper aorm;

	@Autowired
	CardProdunctDefinitionMapper cpdm;

	@Autowired
	CertificateMapper cm;

	@Autowired
	CardControlMapper cacm;

	@Autowired
	CardDataMapper cdm;

	@Autowired
	BusinessMapper bm;

	@Autowired
	CertMapper cem;

	@Autowired
	CardLossMapper clm;

	@Autowired
	CardTypeMapper ctm;

	@Autowired
	CardPhysicsTypeMapper cptm;
	
	@Autowired
	SubaccountPersonalMapper spm;
	
	@Autowired
	AppKindMapper akm;
	
	@Autowired
	CardManageMapper cardManageMapper;

	@Override
	public DwzPage<LossCardInfo> queryUnbindCard(LossCardInfo lci) {
		lci.setCardStatus(CardContants.CARD_STATE_OFFICIAL_LOSS);
		return queryCardInfo(lci);
	}

	@Override
	public ResultVo queryLossCard(LossCardInfo lci) {
		lci.setCardStatus(CardContants.CARD_STATE_NORMAL);
		ResultVo rv = new ResultVo();
		ResultStatus rs = new ResultStatus();
		rs.setCode(HttpContants.RETURN_SUCCESS);
		rs.setMessage("返回成功");

		rv.setResultStatus(rs);
		rv.setServiceObject(queryCardInfo(lci));

		return rv;
	}

	private DwzPage<LossCardInfo> queryCardInfo(LossCardInfo lci) {
		lci.setCardTypeCode(CardContants.CARD_TYPE_REGISTERED);
		lci.setCardStatus2(CardContants.CARD_STATE_ORAL_LOSS);
//		lci.setLossCertType1(CardContants.OFFICIAL_LOSS);
//		lci.setLossCertType2(CardContants.ORAL_LOSS);
		List<ChangeCard> list = ccm.queryLossCard(lci);
		List<LossCardInfo> l = new ArrayList<>();
		if(lci.getLossCertNo()==null||lci.getLossCertNo()==""){
			for (ChangeCard c1 : list) {
				LossCardInfo c2 = new LossCardInfo();
				c2.setCardPName(cpdm.queryCardPCode(c1.getCardpCode()).getCardpName());
				c2.setCardStatusName(CardContants.getCardStatusNameByCode(c1.getCardStatus()));
				c2.setLossTypeCode(c1.getCardStatus());
				c2.setCitizenCardNo(c1.getCitizenCardNo());
				c2.setPaperNo(c1.getPaperNo());
				c2.setPaperTypeName(cm.queryCertificateByCode(c1.getPaperType()).getCertificatesName());
				c2.setCustomerName(c1.getCustomerName());
				c2.setLossCertNo(c1.getCertNo());
				c2.setCardPhysicsTypeName(cptm.queryCardPhysicsTypeByCode(c1.getCardPhysicalType()).getCardTypeName());
				logger.debug("满足的挂失人员："+c1.toString());
				l.add(c2);

			}
		}
		
		DwzPage<LossCardInfo> dp = new DwzPage<LossCardInfo>(lci.getCurrentPage(), lci.getNumPerPage(), l.size());
		dp.setList(l);
		dp.setList(dp.getPagedList());

		return dp;
	}

	@Override
	public ResultVo queryPersonal(String certNo) {
		ResultVo rv = new ResultVo();
		ResultStatus rs = new ResultStatus();
		rs.setCode(HttpContants.RETURN_SUCCESS);
		rs.setMessage("返回成功");
		rv.setResultStatus(rs);
		if (StringUtils.isEmpty(certNo)) {
			rs.setCode(ErrorCode.OBJECT_IS_NULL);
			rs.setMessage("凭证号码为空");
			rv.setResultStatus(rs);
			return rv;
		}

		LossCardVo vo = new LossCardVo();

		Cert c = cem.queryCertByCertNo(certNo);
		if (c == null) {
			rs.setCode(ErrorCode.OBJECT_IS_NULL);
			rs.setMessage("该凭证号码查询无信息");
			rv.setResultStatus(rs);
			return rv;
		}
		if (!CardContants.ORAL_LOSS.equals(c.getCertType()) && !CardContants.OFFICIAL_LOSS.equals(c.getCertType())) {
			rs.setCode(ErrorCode.OBJECT_IS_NULL);
			rs.setMessage("该凭证号码不是挂失凭证");
			rv.setResultStatus(rs);
			return rv;
		}


		CardControl cc = cacm.queryCardControlByCardDataId(c.getCardControlId());
		CardData cd = cdm.queryCardDataById(c.getCardControlId());
		String citizenCardNo = cd.getCitizenCardNo();
		vo.setCardPName(cpdm.queryCardCode(c.getCardpCode()).getCardpName());
		vo.setCardStatusName(CardContants.getCardStatusNameByCode(cc.getCardStatus()));
		vo.setCardTypeName(ctm.queryCardTypeByCode(c.getCardTypecode()).getCardTypeName());
		vo.setCitizenCardNo(citizenCardNo);
		vo.setCustomerName(c.getName());
		vo.setPaperNo(c.getPaperNo());
		vo.setPaperTypeName(cm.queryCertificateByCode(c.getPaperType()).getCertificatesName());
		String crdPhysTp = String.valueOf(citizenCardNo.charAt(2));
		vo.setCardPhysicsName(cptm.queryCardPhysicsTypeByCode(crdPhysTp).getCardTypeName());

		rv.setResultStatus(rs);

		rv.setServiceObject(vo);

		return rv;
	}

	@Override
	@Transactional(rollbackFor=Exception.class,propagation = Propagation.REQUIRED)
	public ResultVo commitLossCardInfo(LossCardInfo lci) throws Exception {
		ResultVo rv = new ResultVo();

		ResultStatus rs = new ResultStatus();

		ActiveUser activeUser = null;
		try {
			activeUser = (ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");

		} catch (UnavailableSecurityManagerException e) {
			e.printStackTrace();
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}
		
		if(activeUser == null){
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}
		
		Date now = new Date();
		
		CardData ca = cdm.queryCardDataByCitizenCardNo(lci.getCitizenCardNo());
		if (ca == null) {
			rs.setCode(ErrorCode.OBJECT_IS_NULL);
			rs.setMessage("查询无市民卡号的信息");
			rv.setResultStatus(rs);
			return rv;
		}

		String paperType = cm.queryCertificateByName(lci.getPaperTypeName()).getCertificateType();
		
		String cardStatus = lci.getCardStatus();
		logger.debug("卡状态："+cardStatus);
		String certType ="";
		if(CardContants.CARD_STATE_OFFICIAL_LOSS.equals(cardStatus)){
			 certType = CardContants.OFFICIAL_LOSS;
		}else if(CardContants.CARD_STATE_ORAL_LOSS.equals(cardStatus)){
			 certType = CardContants.ORAL_LOSS;
		}
		
		logger.debug("凭证类型："+certType);
		int a = cem.checkIsLoss(certType,lci.getCitizenCardNo() );
		logger.debug("是否已经挂失--a-->"+a);
		
		if(a>0){
			rs.setCode(ErrorCode.DUPLICATION_DATA);
			rs.setMessage("卡片["+lci.getCitizenCardNo()+"]已经挂失,请勿重复挂失");
			rv.setResultStatus(rs);
			return rv;
		}
		
		if(CardContants.CARD_STATE_ORAL_LOSS.equals(cardStatus)){
			
			int b = cem.checkIsLoss(CardContants.OFFICIAL_LOSS, lci.getCitizenCardNo());
			logger.debug("是否已经正式挂失--b-->"+b);
			if(b>0){
				rs.setCode(ErrorCode.DUPLICATION_DATA);
				rs.setMessage("卡片["+lci.getCitizenCardNo()+"]已经挂失,请勿重复挂失");
				rv.setResultStatus(rs);
				return rv;
			}
		}
		
		
	
		CardControl cc = cacm.queryCardControlByCitizenCardNo(lci.getCitizenCardNo());

		logger.debug("cardStatus" + cardStatus);
		System.out.println(CardContants.CARD_STATE_ORAL_LOSS.equals(cardStatus));

		if (CardContants.CARD_STATE_ORAL_LOSS.equals(cardStatus)) {// 口头挂失
			cc.setCardStatus(CardContants.CARD_STATE_ORAL_LOSS);// 口头挂失

		} else if (CardContants.CARD_STATE_OFFICIAL_LOSS.equals(cardStatus)) {// 正式挂失
			cc.setCardStatus(CardContants.CARD_STATE_OFFICIAL_LOSS);// 正式挂失

		}
		cc.setIsRead(CardContants.CARD_NO_READ);// 挂失 卡不可讀
		cc.setBlacklistFlag(CardContants.BLACKLIST_FLAG_INNER);// 黑名单标识
		cc.setCardPosition(CardContants.CARD_POSITION_CITIZEN);// 卡位置--市民
		cc.setLastDate(now);
		cc.setLastOperator(activeUser.getUserNo().toString());
		cc.setLossDate(now);
		cc.setLossReason("丢失");
		

		Business b = new Business();
		b.setBusinessNo(SequenceNumberUtil.generatorBusinessNo());
		b.setCustomerNo(ca.getCustomerNo());
		b.setTransCode("交易代码");
		if (CardContants.CARD_STATE_ORAL_LOSS.equals(cardStatus)) {// 口头挂失

		} else if (CardContants.CARD_STATE_OFFICIAL_LOSS.equals(cardStatus)) {// 正式挂失
			if (StringUtils.isNotEmpty(lci.getAgentName()))
				b.setAgentName(lci.getAgentName());
			if (StringUtils.isNotEmpty(lci.getAgentPaperNo()))
				b.setAgentPaperNo(lci.getAgentPaperNo());
			if (StringUtils.isNotEmpty(lci.getAgentPapertype()))
				b.setAgentPapertype(lci.getAgentPapertype());
			if (StringUtils.isNotEmpty(lci.getAgentPhone()))
				b.setAgentPhone(lci.getAgentPhone());
		}

		b.setBusiNum(1);
		b.setTellerNo(activeUser.getUserNo().toString());
		b.setTransDate(now);// 交易日期
		b.setSeqStatus(CardContants.LSZT_NORMAL);
		if (StringUtils.isNoneEmpty(lci.getDesc())) {
			b.setRemark(lci.getDesc());
		} else {
			b.setRemark(CardContants.getCardStatusNameByCode(cardStatus));
		}

		b.setCardControlId(cc.getCardControlId());
		

		Cert ce = new Cert();
		ce.setCertNo(SequenceNumberUtil.generatorCertNo());
		if (CardContants.CARD_STATE_ORAL_LOSS.equals(cardStatus)) {// 口头挂失
			ce.setCertType(CardContants.ORAL_LOSS);
			ce.setData("口头挂失");
			ce.setTransCode("口头挂失");
		} else if (CardContants.CARD_STATE_OFFICIAL_LOSS.equals(cardStatus)) {// 正式挂失
			ce.setCertType(CardContants.OFFICIAL_LOSS);
			String str = "{\"title\":\""+"正式挂失凭证"+"\",\"type\":\""+"lossRegister"+"\",\"certNo\":\""+ce.getCertNo()
			+"\",\"busType\":\""+CardContants.getCertTypeNameByCode(ce.getCertType())+"\",\"cardType\":\""+ca.getCardTypecode()+"\",\"citizenCardNo\":\""+lci.getCitizenCardNo()
			+"\",\"net\":\""+activeUser.getBranchName()+"\",\"operator\":\""+activeUser.getUserNo().toString()+"\",\"date\":\""+DateFormatUtils.format(new Date(), "yyyy-MM-dd")+"\"}";
			ce.setData(str);
			ce.setTransCode("正式挂失");
		}
		ce.setCardpCode(ca.getCardpCode());
		ce.setCardTypecode(ca.getCardTypecode());
		ce.setName(lci.getCustomerName());
		ce.setPaperNo(lci.getPaperNo());
		ce.setPaperType(paperType);
		ce.setPrintCount(1);

		ce.setBranch(activeUser.getBranchName());
		ce.setBranchNo(activeUser.getBranchNo());
		if (StringUtils.isNotEmpty(lci.getAgentName()))
			ce.setAgentName(lci.getAgentName());
		if (StringUtils.isNotEmpty(lci.getAgentPaperNo()))
			ce.setAgentPaperNo(lci.getAgentPaperNo());
		if (StringUtils.isNotEmpty(lci.getAgentPapertype()))
			ce.setAgentPapertype(lci.getAgentPapertype());
		ce.setCrtDate(now);
		ce.setLastDate(now);
		ce.setCrtOperator(activeUser.getUserNo().toString());
		ce.setLastOperator(activeUser.getUserNo().toString());
		//ce.setData("挂失");
		ce.setBusinessNo(b.getBusinessNo());
		ce.setCardControlId(cc.getCardControlId());

		cem.insert(ce);
		
		b.setCertNo(ce.getCertNo());
		bm.insert(b);
		
		
		CardManage cme = new CardManage();
		cme.setProcessId(UUID.randomUUID().toString().replace("-", ""));
		cme.setApplyBranch(activeUser.getBranchName());
		cme.setApplyBranchNo(activeUser.getBranchNo());
		cme.setApplyDate(now);
		cme.setApplyTellerNo(activeUser.getUserNo().toString());
		cme.setBusinessNo(b.getBusinessNo());
		cme.setCertNo(ce.getCertNo());
		// cme.setProcessCode(CardContants.CARD_PROC_APPLY);
		 cme.setProcessName("挂失");
		cme.setCitizenCardNo(lci.getCitizenCardNo());
		// cme.setCardpCode(cardpCode);// 卡产品
		// cme.setCardTypecode(cpd.getCardTypeCode());// 卡类型
		// cme.setCardPosition(CardContants.CARD_POSITION_NO_STORAGE);
		 cme.setCardStatus(cardStatus);
		cme.setApplyWay(CardContants.CLAIM_METHOD_SPORADIC);// 1.零星2.单位规模3.社区规模4.网上规模9.其他规模

		
		cardManageMapper.insert(cme);
		
		cc.setCurrProcId(cme.getProcessId());
		cacm.updateCardControl(cc);
		
		//自行车应用
		AppKind aKind=akm.queryAppKindByAppFalg(AppContants.APP_FLAG_BIKE);
		//应用和钱包
		List<AppOpenReg> la = aorm.queryAppOpenRegByCitizenCardNo(lci.getCitizenCardNo(),AppContants.APP_STATUS_OPEN);//该卡的所有应用
		for(AppOpenReg aor:la){
			if(AppContants.APP_STATUS_OPEN.equals(aor.getAppStatus())){
				aor.setAppStatus(AppContants.APP_STATUS_CLOSE);
				aor.setRemark(AppContants.APP_STATUS_CLOSE_LOSSCARD);
				aor.setLastDate(now);
				aor.setLastOperator(activeUser.getLoginName());
				aorm.update(aor);
			}
		}
		
		List<SubaccountPersonal> lsp = spm.querySubaccountPersonalByCitizenCardNoAndRemark(lci.getCitizenCardNo(),AppContants.APP_STATUS_CLOSE_LOSSCARD);
		for(SubaccountPersonal cardWallet:lsp){
			cardWallet.setLossDate(now);
			cardWallet.setLossStatus(CardContants.CARD_STATE_OFFICIAL_LOSS);
			cardWallet.setAccountStatus(AccountContants.ACCOUNT_STATUS_FROZEN);
			cardWallet.setFreezeAmount(cardWallet.getTotalBalance());
			cardWallet.setFreezeStatus(AccountContants.FREEZE_STATUS_WHOLE);
			cardWallet.setFreezeDate(now);
			spm.update(cardWallet);
		}

		// 黑名单
		BlackListGen bb = blgm.queryBlackListGenBycitizenCardNo(lci.getCitizenCardNo());
		Calendar c = Calendar.getInstance();
		c.setTime(now);
		c.add(Calendar.DAY_OF_MONTH, 1);// 今天+1天
		if (bb == null) {
			bb = new BlackListGen();
			bb.setCitizenCardNo(lci.getCitizenCardNo());
			bb.setCityCode(CardContants.CITY_CODE);
			// bb.setAppType(appType);//置黑应用类型
			// bb.setChipsInno(chipsInno);//接触卡内号
			// bb.setChipsLessInno(chipsLessInno);//非接卡内号
			// bb.setChipsLessNo(chipsLessNo);//非接芯片号
			// bb.setChipsNo(chipsNo);//接触芯片号

			bb.setBlCount(1);// 进黑名单次数
			bb.setBlReCount(0);// 解除黑名单次数
			// bb.setBlReReason(blReReason);//解除黑名单原因
			// bb.setRelieveDate(relieveDate);//解除日期
			if (CardContants.CARD_STATE_ORAL_LOSS.equals(cardStatus)) {// 口头挂失
				bb.setBlReason(BlackListContants.BL_REASON_ORAL_LOSS);
			} else if (CardContants.CARD_STATE_OFFICIAL_LOSS.equals(cardStatus)) {// 正式挂失
				bb.setBlReason(BlackListContants.BL_REASON_OFFICIAL_LOSS);
			}
			bb.setAvailDate(c.getTime());// 生效日期
			bb.setBlackMode(BlackListContants.BL_BLACK_MODE_SYSTEM);// 置黑方式
			bb.setReleaseSys(BlackListContants.BL_PUBLISHING_SYSTEM_LIST_ALl);// 发布系统列表
			bb.setCurStatus(BlackListContants.BL_CUR_STATUS_TAKE_EFFECT);// 当前状态
			bb.setLastBlRcDate(now);// 最后更新日期
			blgm.insert(bb);

		} else {
			bb.setBlCount(bb.getBlCount() + 1);
			bb.setBlReReason(null);// 解除黑名单原因
			bb.setRelieveDate(null);// 解除日期
			if (CardContants.CARD_STATE_ORAL_LOSS.equals(cardStatus)) {// 口头挂失
				bb.setBlReason(BlackListContants.BL_REASON_ORAL_LOSS);
			} else if (CardContants.CARD_STATE_OFFICIAL_LOSS.equals(cardStatus)) {// 正式挂失
				bb.setBlReason(BlackListContants.BL_REASON_OFFICIAL_LOSS);
			}
			bb.setAvailDate(now);// 生效日期
			bb.setBlackMode(BlackListContants.BL_BLACK_MODE_SYSTEM);// 置黑方式
			bb.setReleaseSys(BlackListContants.BL_PUBLISHING_SYSTEM_LIST_ALl);// 发布系统列表
			bb.setCurStatus(BlackListContants.BL_CUR_STATUS_TAKE_EFFECT);// 当前状态
			bb.setLastBlRcDate(now);// 最后更新日期
			blgm.update(bb);

		}

		BlackListRc blr = new BlackListRc();
		// blr.setAppType(appType);//置黑应用类型
		blr.setCitizenCardNo(lci.getCitizenCardNo());// 市民卡号
		blr.setRegisterType(BlackListContants.BL_CUR_STATUS_TAKE_EFFECT);// 登记类型
																			// 1.生效
																			// 2.解除
		blr.setAvailDate(c.getTime());// 生效日期
		// blr.setRelieveDate(relieveDate);//解除日期
		blr.setBlackMode(BlackListContants.BL_BLACK_MODE_SYSTEM);// 置黑方式 0-系统;
																	// 1-手工
		if (CardContants.CARD_STATE_ORAL_LOSS.equals(cardStatus)) {// 口头挂失
			blr.setBlReason(BlackListContants.BL_REASON_ORAL_LOSS);// 进黑名单原因

		} else if (CardContants.CARD_STATE_OFFICIAL_LOSS.equals(cardStatus)) {// 正式挂失
			blr.setBlReason(BlackListContants.BL_REASON_OFFICIAL_LOSS);// 进黑名单原因

		}
		// blr.setBlReReason(blReReason);//解除黑名单原因
		// blr.setCriticalLevel(criticalLevel);//严重级别 0-9, 严重级别由低至高.
		blr.setBlSource(BlackListContants.BL_SOURCE_ALL);// 黑名单来源
		// blr.setReleaseSys(releaseSys);//下发系统
		// blr.setTransCode(transCode);//交易代码
		blr.setBusinessNo(b.getBusinessNo());// 综合业务流水号
		// blr.setDoubtTrNo(doubtTrNo);/可疑交易流水号
		// blr.setssLockTrNo(lockTrNo);//锁卡交易流水号
		blr.setRemark(lci.getDesc());

		blr.setOperDate(now);
		blr.setOpNetworkNo(activeUser.getBranchNo());
		blr.setTellerNo(activeUser.getUserNo().toString());

		blrm.insert(blr);

		// //个人账户表
		// OnlSubaccountPersonal osp =
		// ospm.querySubAccountByCitizenCardNo(ca.getCitizenCardNo());
		// osp.setAccountStatus(AccountContants.ACCOUNT_STATUS_FROZEN);//帐号状态：冻结
		// osp.setFreezeDate(new Date());
		//
		// ospm.update(osp);

		VoucherVo vv = new VoucherVo();
		vv.setCertNo(ce.getCertNo());
		vv.setBusinessTypeName(CardContants.getCertTypeNameByCode(ce.getCertType()));
		vv.setCardType(ca.getCardTypecode());
		vv.setOldCitizenCardNo(lci.getCitizenCardNo());
		// vv.setExpectCardDate(ccc.getTime());
		vv.setDate(DateFormatUtils.format(now, "yyyy-MM-dd"));
		vv.setOperator(activeUser.getUserNo().toString());
		vv.setNet(activeUser.getBranchName());

		rs.setCode(HttpContants.RETURN_SUCCESS);
		rs.setMessage("返回成功");

		rv.setResultStatus(rs);
		rv.setServiceObject(vv);
		
		for(AppOpenReg aor:la){			
			if(aKind.getAppType().toString().equals(aor.getAppType())){
				//请求自行车接口挂失
				bikeService.bikeAppLossAndUnbind(lci.getCitizenCardNo(), "01");
			}			
		}
		return rv;
	}

	@Override
	@Transactional(rollbackFor=Exception.class,propagation = Propagation.REQUIRED)
	public ResultVo commitUnbindCardInfo(LossCardInfo lci)throws Exception {
		ResultVo rv = new ResultVo();
		ResultStatus rs = new ResultStatus();
		ActiveUser activeUser = null;
		try {
			activeUser = (ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");

		} catch (UnavailableSecurityManagerException e) {
			e.printStackTrace();
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}
		
		if(activeUser == null){
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}
		Date now = new Date();
		Calendar c = Calendar.getInstance();
		c.setTime(now);
		c.add(Calendar.DAY_OF_MONTH, 1);// 今天+1天

		CardData ca = cdm.queryCardDataByCitizenCardNo(lci.getCitizenCardNo());


		CardControl cc = cacm.queryCardControlByCitizenCardNo(lci.getCitizenCardNo());
		cc.setCardStatus(CardContants.CARD_STATE_NORMAL);
		cc.setBlacklistFlag(CardContants.BLACKLIST_FLAG_NORMAL);
		cc.setCardPosition(CardContants.CARD_POSITION_CITIZEN);
//		cc.setLossDate(null);
//		cc.setLossReason(null);
		
		
		//应用和钱包
		//自行车应用
		AppKind aKind=akm.queryAppKindByAppFalg(AppContants.APP_FLAG_BIKE);
		List<AppOpenReg> la = aorm.queryAppOpenRegByRemark(lci.getCitizenCardNo(),AppContants.APP_STATUS_CLOSE_LOSSCARD);//该卡的之前挂失的应用
		for(AppOpenReg aor:la){
			if(AppContants.APP_STATUS_CLOSE.equals(aor.getAppStatus())){
				aor.setAppStatus(AppContants.APP_STATUS_OPEN);
				aor.setRemark("解挂");
				aor.setLastDate(now);
				aor.setLastOperator(activeUser.getLoginName());
				aorm.update(aor);
			}
		}
		
		List<SubaccountPersonal> lsp = spm.querySubaccountPersonalByCitizenCardNoAndRemark(lci.getCitizenCardNo(),AppContants.APP_STATUS_CLOSE_LOSSCARD);
		for(SubaccountPersonal cardWallet:lsp){
			cardWallet.setLossDate(now);
			cardWallet.setLossStatus(CardContants.CARD_STATE_NORMAL);
			cardWallet.setAccountStatus(AccountContants.ACCOUNT_STATUS_NORMAL);
			cardWallet.setFreezeAmount(cardWallet.getTotalBalance());
			cardWallet.setFreezeStatus(AccountContants.FREEZE_STATUS_NORMAL);
			cardWallet.setFreezeDate(now);
			spm.update(cardWallet);
		}


		Business b = new Business();
		b.setBusinessNo(SequenceNumberUtil.generatorBusinessNo());
		b.setCustomerNo(ca.getCustomerNo());
		b.setTransCode("交易代码");

		if (StringUtils.isNotEmpty(lci.getAgentName()))
			b.setAgentName(lci.getAgentName());
		if (StringUtils.isNotEmpty(lci.getAgentPaperNo()))
			b.setAgentPaperNo(lci.getAgentPaperNo());
		if (StringUtils.isNotEmpty(lci.getAgentPapertype()))
			b.setAgentPapertype(lci.getAgentPapertype());
		if (StringUtils.isNotEmpty(lci.getAgentPhone()))
			b.setAgentPhone(lci.getAgentPhone());

		b.setBusiNum(1);
		b.setTellerNo(activeUser.getUserNo().toString());
		b.setTransDate(now);// 交易日期
		b.setSeqStatus(CardContants.LSZT_NORMAL);
		b.setRemark(lci.getDesc());
		b.setCardControlId(cc.getCardControlId());
		

		Cert ce = new Cert();
		ce.setCertNo(SequenceNumberUtil.generatorCertNo());
		ce.setCrtDate(now);
		ce.setCertType(CardContants.CARD_UNBIND);
		ce.setLastDate(now);
		ce.setCrtOperator(activeUser.getUserNo().toString());
		ce.setLastOperator(activeUser.getUserNo().toString());
		String str = "{\"title\":\""+"解挂凭证"+"\",\"type\":\""+"lossCancel"+"\",\"certNo\":\""+ce.getCertNo()
		+"\",\"busType\":\""+CardContants.getCertTypeNameByCode(ce.getCertType())+"\",\"cardType\":\""+ca.getCardTypecode()+"\",\"citizenCardNo\":\""+lci.getCitizenCardNo()
		+"\",\"net\":\""+activeUser.getBranchName()+"\",\"operator\":\""+activeUser.getUserNo().toString()+"\",\"date\":\""+DateFormatUtils.format(new Date(), "yyyy-MM-dd")+"\"}";
		ce.setData(str);
		ce.setTransCode("解除挂失");
		//ce.setData("解挂凭证");
		ce.setCardpCode(ca.getCardpCode());
		ce.setCardTypecode(ca.getCardTypecode());
		ce.setName(lci.getCustomerName());
		ce.setPaperNo(lci.getPaperNo());
		ce.setPaperType(cm.queryCertificateByName(lci.getPaperTypeName()).getCertificateType());
		ce.setPrintCount(1);
		ce.setBranch(activeUser.getBranchName());
		ce.setBranchNo(activeUser.getBranchNo());
		if (StringUtils.isNotEmpty(lci.getAgentName()))
			ce.setAgentName(lci.getAgentName());
		if (StringUtils.isNotEmpty(lci.getAgentPaperNo()))
			ce.setAgentPaperNo(lci.getAgentPaperNo());
		if (StringUtils.isNotEmpty(lci.getAgentPapertype()))
			ce.setAgentPapertype(lci.getAgentPapertype());
		ce.setBusinessNo(b.getBusinessNo());
		ce.setCardControlId(cc.getCardControlId());

		ce.setBusinessNo(b.getBusinessNo());
		cem.insert(ce);
		
		b.setCertNo(ce.getCertNo());
		bm.insert(b);
		
		
		CardManage cardManage = new CardManage();
		cardManage.setProcessId(UUID.randomUUID().toString().replace("-", ""));
		cardManage.setApplyBranch(activeUser.getBranchName());
		cardManage.setApplyBranchNo(activeUser.getBranchNo());
		cardManage.setApplyDate(now);
		cardManage.setApplyTellerNo(activeUser.getUserNo().toString());
		cardManage.setBusinessNo(b.getBusinessNo());
		cardManage.setCertNo(ce.getCertNo());
		// cme.setProcessCode(CardContants.CARD_PROC_APPLY);
		cardManage.setProcessName("解挂");
		cardManage.setCitizenCardNo(lci.getCitizenCardNo());
		// cme.setCardpCode(cardpCode);// 卡产品
		// cme.setCardTypecode(cpd.getCardTypeCode());// 卡类型
		// cme.setCardPosition(CardContants.CARD_POSITION_NO_STORAGE);
		cardManage.setCardStatus(CardContants.CARD_STATE_NORMAL);
		cardManage.setApplyWay(CardContants.CLAIM_METHOD_SPORADIC);// 1.零星2.单位规模3.社区规模4.网上规模9.其他规模
		cardManage.setBusinessNo(b.getBusinessNo());
		cardManageMapper.insert(cardManage);

		
		cc.setCurrProcId(cardManage.getProcessId());
		cacm.updateCardControl(cc);
		
		BlackListRc blr = new BlackListRc();
		// blr.setAppType(appType);//置黑应用类型
		blr.setCitizenCardNo(lci.getCitizenCardNo());// 市民卡号
		blr.setRegisterType(BlackListContants.BL_CUR_STATUS_Relieve);// 登记类型
																		// 1.生效
		blr.setRelieveDate(c.getTime());// 解除日期
		blr.setBlackMode(BlackListContants.BL_BLACK_MODE_SYSTEM);// 置黑方式 0-系统;
																	// blr.setBlReason(blReason);//进黑名单原因
		blr.setBlReReason(BlackListContants.BL_RE_REASON_COUNTER_HANGING);// 解除黑名单原因
		// blr.setCriticalLevel(criticalLevel);//严重级别 0-9, 严重级别由低至高.
		blr.setBlSource(BlackListContants.BL_SOURCE_ALL);// 黑名单来源
		// blr.setReleaseSys(releaseSys);//下发系统
		// blr.setTransCode(transCode);//交易代码
		blr.setBusinessNo(b.getBusinessNo());// 综合业务流水号
		// blr.setDoubtTrNo(doubtTrNo);/可疑交易流水号
		// blr.setssLockTrNo(lockTrNo);//锁卡交易流水号
		blr.setRemark(lci.getDesc());

		blr.setOperDate(now);
		blr.setOpNetworkNo(activeUser.getBranchNo());
		blr.setTellerNo(activeUser.getUserNo().toString());

		blrm.insert(blr);

		BlackListGen bb = blgm.queryBlackListGenBycitizenCardNo(lci.getCitizenCardNo());
		bb.setBlReReason(BlackListContants.BL_RE_REASON_COUNTER_HANGING);
		bb.setCurStatus(BlackListContants.BL_CUR_STATUS_Relieve);
		bb.setRelieveDate(c.getTime());
		bb.setLastBlRcDate(now);

		blgm.update(bb);

		VoucherVo vv = new VoucherVo();
		vv.setCertNo(ce.getCertNo());
		vv.setBusinessTypeName(CardContants.getCertTypeNameByCode(ce.getCertType()));
		vv.setCardType(ca.getCardTypecode());
		vv.setOldCitizenCardNo(lci.getCitizenCardNo());
		// vv.setExpectCardDate(c.getTime());
		vv.setDate(DateFormatUtils.format(now, "yyyy-MM-dd"));
		vv.setOperator(activeUser.getUserNo().toString());
		vv.setNet(activeUser.getBranchName());

		rs.setCode(HttpContants.RETURN_SUCCESS);
		rs.setMessage("返回成功");

		rv.setResultStatus(rs);
		rv.setServiceObject(vv);
		
		for(AppOpenReg aor:la){
			if(aor.getAppType().equals(aKind.getAppType().toString())){
				//请求自行车接口解挂
				bikeService.bikeAppLossAndUnbind(lci.getCitizenCardNo(), "00");
			}			
		}

		return rv;
	}

	
	

}
